/*
** main.c for ololol in /home/phand/exotest/tek2/prog-elem/trade
** 
** Made by david phan
** Login   <phan_d@epitech.net>
** 
** Started on  Tue Apr 17 16:38:24 2012 david phan
** Last update Fri Jun  1 22:12:16 2012 david phan
*/

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
#include <stdlib.h>

#include "h_trade.h"

#define BUFFER_SIZE	512

static void	do_the_magic(t_trade *trade, t_etude *etude)
{
  if (trade->current_day < trade->total_days / 4)
    {
      fill_etude(trade->current_auction, etude);
      write(1, "passe\n", strlen("passe\n"));
      return;
    }
  fill_etude(trade->current_auction, etude);
  if (trade->current_money > trade->current_auction && trade->nb_auction == 0)
    {
      trade->nb_auction += 1;
      write(1, "buy 1\n", strlen("buy 1\n"));
      trade->current_money -= trade->current_auction;
      trade->last_bought = trade->current_auction;
    }
  else if (trade->last_bought < trade->current_auction)
    {
      trade->nb_auction -= 1;
      write(1, "sell 1\n", strlen("sell 1\n"));
      trade->current_money += trade->current_auction;
      return;
    }
  write(1, "passe\n", strlen("passe\n"));
}

int		main()
{
  t_trade	trade;
  t_etude	etude;
  char		buff[BUFFER_SIZE];
  int		end;

  init_trade(&trade);
  init_etude(&etude);
  while (trade.current_day < trade.total_days - 1) 
    {
      do_the_magic(&trade, &etude);
      end = read(0, buff, BUFFER_SIZE);
      buff[end] = '\0';
      trade.current_day++;
    }
  if (trade.nb_auction > 0)
    write(1, "sell 1\n", strlen("sell 1\n"));
  return (0);
}
